package http

import (
	"context"
	"fmt"
	"io"
	"net/http"

	"github.com/labstack/echo/v4"

	generated_v8s_api "v8s-api/rest-api/target/generated-sources"
	"v8s-ssp-proxy/rest/target/generated-sources"
)

type (
	handlers struct {
		client generated_v8s_api.ClientInterface
	}
)

func NewHandlers(client generated_v8s_api.ClientInterface) *handlers {
	return &handlers{
		client: client,
	}
}

func (h *handlers) GetComposeSchema(ctx echo.Context) error {
	compose, err := h.getComposeSchema(ctx.Request().Context())
	if err != nil {
		return ctx.JSON(http.StatusInternalServerError, generated.ErrorDto{
			Code:    "FAILED_TO_GET_COMPOSE",
			Message: err.Error(),
		})
	}

	return ctx.JSON(http.StatusOK, compose)
}

func (h *handlers) getComposeSchema(ctx context.Context) (generated.DropAppComposeSchema, error) {
	response, err := h.client.GetComposeSchema(ctx)
	if err != nil {
		return "", fmt.Errorf("cannot get compose scheme : %w", err)
	}

	defer func() {
		_ = response.Body.Close()
	}()

	data, err := io.ReadAll(response.Body)
	if err != nil {
		return "", fmt.Errorf("failed to read body from response: %w", err)
	}

	if response.StatusCode != 200 {
		return "", fmt.Errorf("cannot get compose schema from controller: status '%s', response '%s'", response.Status, string(data))
	}

	return generated.DropAppComposeSchema(data), nil
}
